package com.belizer.demo.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Demo5 {

    public static void main(String[] args) throws InterruptedException{
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<Callable<String>> tasks = new ArrayList<>();
//        tasks.add(()->{
//            System.out.println("task 1 execute success");
//            return "0";
//        });
//        tasks.add(()->{
//            int i = 1/0;
//
//            return "0";
//        });

        MyTask1 myTask1 = new MyTask1("1");
        MyTask2 myTask2 = new MyTask2("2");
        tasks.add(myTask1);
        tasks.add(myTask2);

        List<Future<String>> futures = executorService.invokeAll(tasks);
        for (Future<String> future:futures){
            try {
                String s = future.get();
                System.out.println(s);
            } catch (ExecutionException e) {

                System.out.println(e.getCause().getMessage());
            }
        }
    }


    static abstract class BaseTask<V> implements Callable<V>{
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        private String name;

        BaseTask(String name) {
            this.name = name;
        }
    }

    static class MyTask1 extends BaseTask<String>{

         MyTask1(String name) {
            super(name);
        }

        @Override
        public String call(){
            System.out.println("task "+super.getName()+" execute success");
            return "0";
        }
    }

    static class MyTask2 extends BaseTask<String>{

        MyTask2(String name) {
            super(name);
        }

        @Override
        public String call(){
            int i = 1/0;
            return "0";
        }
    }
}

